
package avenue;

import java.util.List;
import javax.persistence.EntityManager;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import model.AppUser;
import model.DBManager;

/**
 * @author Team-2
 */
public class LoginForm extends javax.swing.JFrame {
    
    /**
     * Creates new form LoginForm
     */
    public LoginForm() {
               
        em = DBManager.em;
        initComponents();
    }
    
     public LoginForm(JFrame parent) {
        em = DBManager.em;
        this.parent=(Avenue)parent;    
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButton2 = new javax.swing.JButton();
        passwordField = new javax.swing.JPasswordField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        userNameField = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Είσοδος Χρήστη");
        setAlwaysOnTop(true);
        setResizable(false);

        jButton2.setText("Ακυρο");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        passwordField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                passwordFieldKeyPressed(evt);
            }
        });

        jLabel1.setText("Username");

        jLabel2.setText("Password");

        jButton1.setText("OK");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2))
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, 1, Short.MAX_VALUE)
                    .addComponent(userNameField, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(71, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(53, 53, 53)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2))
                .addContainerGap(24, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed

        loginAction();        
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        System.exit(0);
    }//GEN-LAST:event_jButton2ActionPerformed

    private void passwordFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_passwordFieldKeyPressed

        if (evt.getKeyCode() == 10) { //pressed Enter key
            loginAction();
        }
    }//GEN-LAST:event_passwordFieldKeyPressed
 /**
  * Set the Menu persmissions after user login as the RolePermissions assign
  */
    private void setMenuPermissions() {
        
        parent.getjMenuUsers().setEnabled(Session.doesSessionUserHasPermission(Session.USERS_MODULE));
        parent.usersIconButton.setEnabled(Session.doesSessionUserHasPermission(Session.USERS_MODULE));
        parent.getjMenuCustomers().setEnabled(Session.doesSessionUserHasPermission(Session.CUSTOMERS_MODULE));
        parent.customersIconButton.setEnabled(Session.doesSessionUserHasPermission(Session.CUSTOMERS_MODULE));
        parent.getjMenuRoles().setEnabled(Session.doesSessionUserHasPermission(Session.ROLES_MODULE));
        parent.rolesIconButton.setEnabled(Session.doesSessionUserHasPermission(Session.ROLES_MODULE));
        parent.getjMenuPrograms().setEnabled(Session.doesSessionUserHasPermission(Session.PROGRAMS_MODULE));
        parent.programsIconButton.setEnabled(Session.doesSessionUserHasPermission(Session.PROGRAMS_MODULE));
        parent.getjMenuCollectToll().setEnabled(Session.doesSessionUserHasPermission(Session.TOLL_COLLECTION_MODULE));
        parent.tollIconButton.setEnabled(Session.doesSessionUserHasPermission(Session.TOLL_COLLECTION_MODULE));
        parent.getjMenuCardTransactions().setEnabled(Session.doesSessionUserHasPermission(Session.LOG_MODULE));
        parent.cardTransIconButton.setEnabled(Session.doesSessionUserHasPermission(Session.LOG_MODULE));
        parent.getjMenuCustomerTransactions().setEnabled(Session.doesSessionUserHasPermission(Session.LOG_MODULE)); 
        parent.customerTransIconButton.setEnabled(Session.doesSessionUserHasPermission(Session.LOG_MODULE));
        
    }
    
    
    /**
     * User Login check
     */    
    private void loginAction() {

        query1 = em.createQuery("select u from AppUser u where u.userName=:userName and u.password=:password").setParameter("userName",userNameField.getText()).setParameter("password",passwordField.getText());
        list1 =  query1.getResultList();
        if (list1.size()==1) {
            Session.loginUser = (AppUser)list1.get(0);           
            setMenuPermissions(); //set menu permitions
            //Set info fields of station and user name in avenue form
            String stationName = Session.loginUser.getStationId().getDescription();
            String userName = Session.loginUser.getFName() + " " + Session.loginUser.getLName();           
            parent.setInfoFields(stationName, userName);
            parent.setEnabled(true); // enable parent form           
            dispose();
        } else
        {
            String message = "Τα στοιχεία εισόδου είναι λανθασμένα!";
            JOptionPane.showMessageDialog(this, message, "Προσοχή", 0);          
        }
    }    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                //new LoginForm().setVisible(true);
                LoginForm  loginForm = new LoginForm();
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JTextField userNameField;
    // End of variables declaration//GEN-END:variables
    private javax.persistence.Query query1;
    List list1;
    EntityManager em;
    Avenue parent;
}
